package com.uobgroup.ews.uam.web;

import java.util.Calendar;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.uobgroup.ews.uam.core.enums.OperateType;
import com.uobgroup.ews.uam.core.service.ChangeLogService;
import com.uobgroup.ews.uam.web.dto.SearchChangeLog;

@RequestMapping("/changelogs")
@Controller
public class ChangeLogController {

   @Autowired
   private ChangeLogService changeLogService;

   //private static Logger logger = Logger.getLogger(ChangeLogController.class);

   @RequestMapping(produces = "text/html")
   public String list(@RequestParam(value = "page", required = false) Integer page,
         @RequestParam(value = "size", required = false) Integer size, Model uiModel, SearchChangeLog searchChangeLog) {
      if (searchChangeLog == null) {
         searchChangeLog = new SearchChangeLog();
         searchChangeLog.setSearchAction(null);
         searchChangeLog.setSearchUserId("");
         searchChangeLog.setSearchFromDate(null);
         searchChangeLog.setSearchToDate(null);
      }

      if (page == null) {
         page = 1;
      }
      if (size == null) {
         size = 10;
      }

      if(searchChangeLog.getSearchToDate() != null){
         Calendar calendar = Calendar.getInstance();
         calendar.setTimeInMillis(searchChangeLog.getSearchToDate().getTime());
         calendar.set(Calendar.HOUR_OF_DAY, 23);
         calendar.set(Calendar.MINUTE, 59);
         calendar.set(Calendar.SECOND, 59);
         searchChangeLog.setSearchToDate(calendar.getTime());
      }
      int sizeNo = size == null ? 10 : size.intValue();
      final int firstResult = page == null ? 0 : (page.intValue() - 1) * sizeNo;
      searchChangeLog.setChangeLogs(changeLogService.find(OperateType.getType(searchChangeLog.getSearchAction()),
            searchChangeLog.getSearchUserId(), searchChangeLog.getSearchFromDate(), searchChangeLog.getSearchToDate(), firstResult, sizeNo));
      float nrOfPages = (float) changeLogService.count(OperateType.getType(searchChangeLog.getSearchAction()),
            searchChangeLog.getSearchUserId(), searchChangeLog.getSearchFromDate(), searchChangeLog.getSearchToDate()) / sizeNo;
      uiModel.addAttribute("maxPages", (int) ((nrOfPages > (int) nrOfPages || nrOfPages == 0.0) ? nrOfPages + 1
            : nrOfPages));
      uiModel.addAttribute("searchChangeLog", searchChangeLog);
      uiModel.addAttribute("operateTypes", OperateType.getActionList(true));
      return "changelogs/list";
   }
}
